package com.metacube.metaconnect.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.metacube.metaconnect.Service.UserInformationService;
import com.metacube.metaconnect.model.FileUpdate;
import java.util.Calendar;

public class FileUpdateAction extends Action {

	/*
	 * change profile picture of user
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		if (form == null
				|| request.getSession().getAttribute("emailId") == null)
			return mapping.findForward("failure");
		else {
			FileUpdate update = (FileUpdate) form;

			FileOutputStream outputStream = null;
			FormFile formFile = null;

			try {

				formFile = update.getFile();
				int temp = (int) (Math.random() * 1000 + Math.random() * 2000 + Math
						.random() * 3000);

				if (formFile == null)
					return mapping.findForward("failure");
				String imgName = temp
						+ request.getSession().getAttribute("emailId")
								.toString()
						+ formFile.getFileName().substring(
								formFile.getFileName().lastIndexOf("."));

				String res = formFile + "";
				if (!res.equals("")) {

					String path = getServlet().getServletContext().getRealPath(
							"Upload")
							+ "\\" + imgName;
					outputStream = new FileOutputStream(new File(path));
					outputStream.write(formFile.getFileData());
				}
				String email = request.getSession().getAttribute("emailId")
						.toString();

				boolean result = new UserInformationService().updateFile(
						update, imgName, email);
				if (result) {
					request.setAttribute("updatePic", "yes");
					return mapping.findForward("success");
				} else {
					request.setAttribute("errorInUpdatePic",
							"Something Went Wrong!!! Pic is not uploaded");
					return mapping.findForward("failure");
				}
			} finally {
				if (outputStream != null) {
					outputStream.close();
				}
			}
		}

	}
}
